# @Author: 唐奇才
# @Time: 2021/6/8 23:29
# @File: 17.基于SK-learn Label Propagation的半监督算法实现.py
# @Software: PyCharm

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
# 新版本sklearn支持的_label_propagation  _label 传播
from sklearn.semi_supervised import _label_propagation


rng = np.random.RandomState(0)  #生成随机数种子
iris = datasets.load_iris()  #载入iris数据集
X = iris.data[:, :2]  #设置横纵坐标
y = iris.target


h = .02  #设置步长
#生成不同的纵坐标
y_30 = np.copy(y)
y_30[rng.rand(len(y)) < 0.3] = -1
y_50 = np.copy(y)
y_50[rng.rand(len(y)) < 0.5] = -1
# 创建一个基于该数据的SVM实例
ls30 = (_label_propagation.LabelSpreading().fit(X, y_30),
        y_30)
ls50 = (_label_propagation.LabelSpreading().fit(X, y_50),
        y_50)
ls100 = (_label_propagation.LabelSpreading().fit(X, y), y)
rbf_svc = (svm.SVC(kernel='rbf').fit(X, y), y)

# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),  #数据矢量化
                     np.arange(y_min, y_max, h))
# 定义图的标题
titles = ['Label Spreading 30% data',
          'Label Spreading 50% data',
          'Label Spreading 100% data',
          'SVC with rbf kernel']
#定义图的颜色
color_map = {-1: (1, 1, 1), 0: (0, 0, .9), 1: (1, 0, 0), 2: (.8, .6, 0)}
#创建子图
for i, (clf, y_train) in enumerate((ls30, ls50, ls100, rbf_svc)):
    # P绘制决策边界
    # 按步长画点
    plt.subplot(2, 2, i + 1)
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    # 输出结果
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
    plt.axis('off')
    # 输出训练点
    colors = [color_map[y] for y in y_train]
    plt.scatter(X[:, 0], X[:, 1], c=colors, edgecolors='black')
    # 生成标题
    plt.title(titles[i])
plt.suptitle("Unlabeled points are colored white", y=0.1)
plt.show()  #显示结果图